﻿Imports System.Data.OleDb
Public Class Ratecomments
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Rating2.MaxRating = 5
        If Not IsPostBack Then
            SetCurrentRating()
        End If
    End Sub

    Private Sub SetCurrentRating()

        Dim oleDbConn = New OleDbConnection(ConfigurationManager.ConnectionStrings("DealsDbConnection").ConnectionString)
        Dim sql = "SELECT AVG(Rating) AS Rating FROM(Userrating) GROUP BY Dealid, Rater"
        Dim oleDbcmd = New OleDbCommand(sql, oleDbConn)
        oleDbConn.Open()
        Dim rating = oleDbcmd.ExecuteScalar()
        oleDbConn.Close()
        oleDbcmd.Dispose()
        oleDbConn.Dispose()

        Rating2.CurrentRating = rating
        Label1.Text = "Current rating: " + rating.ToString()
    End Sub

    Protected Sub Rating2_Changed(ByVal sender As Object, ByVal e As AjaxControlToolkit.RatingEventArgs) Handles Rating2.Changed


        Dim oleDbConn = New OleDbConnection(ConfigurationManager.ConnectionStrings("DealsDbConnection").ConnectionString)
        Dim sql = "DELETE * FROM Userrating WHERE Rater = @f1 AND Dealid = @f2"
        Dim oleDbcmd = New OleDbCommand(sql, oleDbConn)
        oleDbConn.Open()
        oleDbcmd.Parameters.AddWithValue("@f1", User.Identity.Name)
        oleDbcmd.Parameters.AddWithValue("@f2", Request.Params("ID"))
        oleDbcmd.ExecuteNonQuery()
        oleDbcmd.Dispose()
        oleDbConn.Close()

        sql = "INSERT INTO  Userrating(Rating,Rater,Dealid) VALUES (@f1,@f2,@f3)"
        oleDbcmd = New OleDbCommand(sql, oleDbConn)
        oleDbConn.Open()

        oleDbcmd.Parameters.AddWithValue("@f1", e.Value)
        oleDbcmd.Parameters.AddWithValue("@f2", User.Identity.Name)
        oleDbcmd.Parameters.AddWithValue("@f3", Request.Params("ID"))
        oleDbcmd.ExecuteNonQuery()
        oleDbConn.Close()
        oleDbcmd.Dispose()
        oleDbConn.Dispose()

        SetCurrentRating()
    End Sub
End Class